<template>
  <view>
    <el-dialog v-model="showDetail" @closed="cacel" width="80vw" top="7vh" title="商品管理">
      <template #header>
        <el-row type="flex" justify="end">
          <el-button type="default" @click="shareLink" >
            <Icon class="mr-5px" icon="ep:share"/>分享
          </el-button>
          <el-button v-if="isEdit" type="danger" @click="deleteProduct">
            <Icon class="mr-5px" icon="ep:delete" />删除
          </el-button>
        </el-row>
      </template>
      <el-form id="pdfDom" :model="productInfo" ref="proFormRef" label-position="top" :rules="rules"
        style="height: 650px; overflow: auto">
        <el-tag type="info">商品管理</el-tag>
        <el-form-item prop="goods" v-if="!isAdd">
          <el-text class="goods-title">{{ productInfo.goods }}</el-text>
        </el-form-item>
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template #title>
              <span class="collapse-title">基本信息</span>
            </template>
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item required label="编号" prop="number">
                  <span v-if="!isEdit&&!isAdd">{{ productInfo.number }}</span>
                  <el-input v-model="productInfo.number" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="品名" prop="goods">
                  <span v-if="!isEdit&&!isAdd">{{ productInfo.goods }}</span>
                  <el-input v-model="productInfo.goods" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="规格" prop="specification">
                  <span v-if="!isEdit&&!isAdd">{{ productInfo.specification }}</span>
                  <el-input v-model="productInfo.specification" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="计量单位" prop="unit">
                  <dict-tag v-if="!isEdit&&!isAdd" :type="DICT_TYPE.HKB_GOODS_UNIT" :value="productInfo.unit" />
                  <el-select v-model="productInfo.unit" :placeholder="$t(`global.select`)" clearable v-else>
                    <el-option v-for="dict in getStrDictOptions(DICT_TYPE.HKB_GOODS_UNIT)" :key="dict.value + ''"
                      :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider border-style="dotted" />
            <el-form-item label="产品类别" prop="goodsType">
              <dict-tag v-if="!isEdit&&!isAdd" :type="DICT_TYPE.HKB_GOODS_TYPE" :value="productInfo.goodsType" />
              <el-select v-model="productInfo.goodsType" :placeholder="$t(`global.select`)" clearable v-else>
                <el-option v-for="dict in getStrDictOptions(DICT_TYPE.HKB_GOODS_TYPE)" :key="dict.value + ''"
                  :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-divider border-style="dotted" />
            <el-form-item label="描述" prop="comment" v-if="showDetail">
              <span v-if="!isEdit&&!isAdd" v-html="productInfo.comment"></span>
              <!--富文本编辑器组件-->
              <Editor v-model="productInfo.comment" v-else :toolConfig="toolbarConfig" style="width: 100%" height="300px"/>
            </el-form-item>
            <el-divider border-style="dotted" />
            <el-row>
              <el-col :span="18">
                <el-form-item label="附件" prop="id">
                  <draggable v-model="fileDetailList" item-key="index" :animation="200" filter=".nodraggable"
                    ghost-class="draggable-ghost" :force-fallback="true" group="component" style="display: flex">
                    <template #item="{ element, index }">
                      <view class="image-box" :class="(isEdit || isAdd) ? '' : 'nodraggable'">
                        <slot :element="element" :index="index">
                          <el-image v-if="element.name.endsWith('jpg') ||
                            element.name.endsWith('png') ||
                            element.name.endsWith('jpeg')
                            " :src="element.url" alt="" :preview-src-list="[element.url]" class="file-image"
                            fit="cover" />
                          <el-image v-else :src="fileImage" class="file-image file" fit="contain" />
                          <view class="hover-box">
                            <el-input v-model="element.name" class="input" v-if="isEdit || isAdd"/>
                            <view class="input" v-else>{{ element.name }}</view>
                            <el-row type="flex" justify="end">
                              <el-button :icon="Delete" @click="handleRemove(index)" v-if="isEdit || isAdd"/>
                              <el-button :icon="Download" @click="handleDownload(element.url)" />
                            </el-row>
                          </view>
                        </slot>
                      </view>
                    </template>
                  </draggable>
                  <el-upload v-if="isEdit || isAdd" action="#" list-type="picture-card" :file-list="fileDetailList"
                    :auto-upload="false" :multiple="true" :show-file-list="false" :on-change="onchangeFile">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="!isAdd">
                <el-form-item label="条码" prop="qrcode">
                  <el-image :preview-src-list="['data:image/jpeg;base64,' + productInfo.qrcode]"
                    :src="'data:image/jpeg;base64,' + productInfo.qrcode" style="width: 150px; height: 150px" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <el-row type="flex" justify="center" style="margin-top: 20px">
        <el-button type="primary" v-show="isEdit||isAdd" :loading="buttonLoading" @click="uploadFile">{{ $t(`global.verify`) }}</el-button>
        <el-button @click="cacel">{{$t(`global.cancel`)}}</el-button>
      </el-row>
    </el-dialog>

    <el-dialog v-model="shareDialog" @closed="cacelShare" >
      <el-input v-model="shareLinks" />
      <el-row type="flex" justify="center" style="margin-top: 20px">
        <el-button type="primary" @click="copyLink">复制链接</el-button>
        <el-button @click="cacelShare">{{$t(`global.cancel`)}}</el-button>
      </el-row>
    </el-dialog>
  </view>
</template>

<script setup lang="ts">
import { Delete, Download, Plus } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { ref } from 'vue'
import * as productApi from '@/service/api/hkb/product'
import * as fileUpload from '@/service/api/infra/file'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import type { goodsVO } from '../../types'
import type { FormInstance, FormRules } from 'element-plus'

import { REFRESH_CONFIG, getServiceEnvConfig } from '@/config'
const { url } = getServiceEnvConfig(import.meta.env)
// defineOptions({ name: 'productDetail' })

const props = defineProps({
  isAdd: Boolean,
  isEdit: Boolean,
  modelValue: Boolean
})

const message = useMessage() // 消息弹窗

const emits = defineEmits(['submitUpdate', 'update:modelValue'])

const showDetail = ref(props.modelValue)
import fileImage from '@/static/images/file.png'
const fileDetailList = ref<any[]>([])
const buttonLoading = ref(false) //按钮的加载
const activeNames = ref('1')
const flag = ref(false)
const shareDialog = ref(false)
const shareLinks = ref('')

const initForm = ref<goodsVO>({
  id: undefined,
  number: undefined,
  goods: '',
  specification: '',
  unit: '',
  qrcode: '',
  goodsFiles: [],
  goodsType: '',
  coverpath: '',
  comment: ''
})
const productInfo = ref<goodsVO>({
  id: undefined,
  number: undefined,
  goods: '',
  specification: '',
  unit: '',
  qrcode: '',
  goodsFiles: [],
  goodsType: '',
  coverpath: '',
  comment: ''
})
const rules = reactive<FormRules<goodsVO>>({
  number: [
    { required: true, message: '请输入商品编号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3-20之间', trigger: 'blur' },
  ],
  goods: [
    {
      required: true,
      message: '请输入商品品名',
      trigger: 'blur',
    },
  ],
  specification: [
    {
      required: true,
      message: '请输入商品规格',
      trigger: 'blur',
    },
  ],
  unit: [
    {
      required: true,
      message: '请选择商品单位',
      trigger: 'change',
    },
  ],
  goodsType: [
    {
      required: true,
      message: '请选择产品类别',
      trigger: 'change',
    }
  ]
})
const proFormRef = ref<FormInstance>()

const initFormValue = (val) => {
  proFormRef.value?.resetFields()
  productInfo.value = JSON.parse(JSON.stringify(val))
  fileDetailList.value = JSON.parse(
    JSON.stringify(productInfo.value).replaceAll('filePath', 'url').replaceAll('fileName', 'name')
  ).goodsFiles
  productInfo.value.goodsFiles = []
}

defineExpose({
  initFormValue
})

import { IToolbarConfig } from '@wangeditor/editor'
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: [
    'uploadVideo', // 排除菜单组，写菜单组 key 的值即可
    "group-video",
    'group-image',
    'emotion',
    'todo',
    'insertLink',
    'insertTable',
    'divider',
    'codeBlock'
  ]
}
/** 关闭弹窗 **/
const cacel = () => {
  proFormRef.value?.resetFields()
  productInfo.value = { ...initForm.value }
  fileDetailList.value = []
  showDetail.value = false
  emits('update:modelValue', showDetail.value)
}

/** 返回表单信息信息 **/
const submitUpdate = async () => {
  await proFormRef.value?.validate(async (valid) => {
    if (valid) {
      buttonLoading.value = true
      if (productInfo.value.id) {
        await productApi
          .editProduct(productInfo.value)
          .then((res) => {
            if (res) {
              message.success('修改成功')
            } else {
              message.warning('修改失败')
            }
          })
          .finally(() => ((buttonLoading.value = false), cacel()))
      } else {
        await productApi
          .addProduct(productInfo.value)
          .then((res) => {
            if (res) {
              message.success('新增成功')
            } else {
              message.warning('新增失败')
            }
          })
          .finally(() => ((buttonLoading.value = false), cacel()))
      }
      emits('submitUpdate')
    }
  })
}

/** 上传文件 **/
const uploadFile = async () => {
  proFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (fileDetailList.value.length > 0) {
        let formdata = new FormData()
        fileDetailList.value.map((item: any) => {
          if (item.raw) {
            formdata.append('files', item.raw)
          } else {
            item = JSON.parse(
              JSON.stringify(item).replaceAll('url', 'filePath').replaceAll('name', 'fileName')
            )
            productInfo.value.goodsFiles.push(item)
          }
        })
        if (flag.value) {
          const res = await fileUpload.updateFileBatch(formdata)
          flag.value = false
          let data = res.data.data
          data.map((item: any) => {
            let obj = {
              fileName: '',
              filePath: '',
              fileType: ''
            }
            obj.fileName = item.name
            obj.fileType = item.type
            obj.filePath = url + '/' + item.url
            productInfo.value.goodsFiles.push(obj)
          })
        }
      }
      submitUpdate()
    }
  })
}

/** 新增时删除附件 **/
const handleRemove = (index: number) => {
  fileDetailList.value.splice(index, 1)
}

/** 添加文件到文件列表 **/
const onchangeFile = (file: any) => {
  fileDetailList.value.push(file)
  flag.value = true
}


/** 删除 **/
const deleteProduct = async () => {
  try {
    // 二次确认
    await message.confirm('确认要立即删除这条数据吗?', '温馨提示')
    // 提交执行
    productApi.deleteProduct(productInfo.value.id).then((res) => {
      if (res) {
        message.success('删除成功')
      } else {
        message.warning('删除失败')
      }
    }).finally(() => (cacel(), emits('submitUpdate')))
  } catch (error) { }
}

/** 分享链接 **/
const shareLink = () => {
  console.log(12312)
  shareDialog.value = true
  shareLinks.value = window.location.href + '?shareId=' + productInfo.value.id
  console.log(window)
}

/** 取消分享 **/
const cacelShare = () => {
  shareDialog.value = false
}

/** 复制链接 **/
const copyLink = () => {
  navigator.clipboard.writeText(shareLinks.value);
  message.success('链接已复制到剪切板')
}
/** 下载 **/
const handleDownload = (url: any) => {
  window.open(url)
}

</script>

<style scoped lang="scss">
.goods-title {
  color: #000;
  font-size: 24px;
  margin: 10px 0 10px;
}

.collapse-title {
  color: #000;
  font-size: 15px;
  font-weight: 600;
}

.image-box {
  position: relative;
  width: 180px;
  height: 148px;
  margin-right: 10px;

  &:hover .hover-box {
    display: block;
    .input {
      color: #fff
    }
  }
}

.file-image {
  width: 100%;
  height: 100%;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;

  &.file ::v-deep(.el-image__inner) {
    width: 60px;
  }
}

.hover-box {
  display: none;
  position: absolute;
  top: 0;
  background: #00000090;
  height: 150px;
  width: 182px;
  box-sizing: border-box;
  padding: 10px;

  ::v-deep(.input) {
    margin-bottom: 60px;
  }
}
</style>
